﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MiniFox.Components.Configurations;
using MiniFox.Components;
using MiniFox.Configurations;
using MiniFox.Utility;
using MiniFox.Web.AppStarting;
using MiniFox.Web.Configurations;

namespace MiniFox.Web
{
    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="hostEnvironment"></param>
        public Startup(IConfiguration configuration, IWebHostEnvironment hostEnvironment)
        {
            this.Configuration = configuration;
            this.Environment = hostEnvironment;
            this.HttpStarts = new List<IHttpStart>();
        }
        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }
        /// <summary>
        /// 
        /// </summary>
        public IWebHostEnvironment Environment { get; }
        /// <summary>
        /// 
        /// </summary>
        public List<IHttpStart> HttpStarts
        {
            get;
        }

        internal void Initialize()
        {
            WebConfiguration webConfiguration = ConfigurationFactory.GetConfig<WebConfiguration>();
            //内置start
            this.HttpStarts.Add(new RegisterMiddleware(this.Configuration, this.Environment, webConfiguration));
            this.HttpStarts.Add(new RegisterStaticResource(this.Configuration, this.Environment, webConfiguration));
            this.HttpStarts.Add(new RegisterMvc(this.Configuration, this.Environment, webConfiguration));
            this.HttpStarts.Add(new RegisterRoutes(this.Configuration, this.Environment, webConfiguration));
            //扩展start
            webConfiguration.HttpStarts.ForEach(setting =>
            {
                Type type = setting;
                var httpStart = Activator.CreateInstance(type, this.Configuration, this.Environment, webConfiguration) as IHttpStart;
                HttpStarts.Add(httpStart);
            });

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            this.HttpStarts.ForEach(httpStart => 
            {
                httpStart.OnServicesConfiguring(services);
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public void Configure(IApplicationBuilder app)
        {
            this.HttpStarts.ForEach((httpStart) =>
            {
                httpStart.OnApplicationConfiguring(app);
            });
        }
    }
}
